package message.handler;

import message.Message;

import comunity.Community;
import comunity.GPSLocation;
import comunity.Status;

public class BroadcastHandler implements Runnable {

	String sender;
	String text;

	public BroadcastHandler(String sender, String text) {
		this.sender = sender;
		this.text = text;
	}

	@Override
	public void run() {
		Community community = Community.obtainCommunity();
		if (community.size() == 1)
			return;

		for (String currentUsername : community.getUsers()) {
			String receiver = currentUsername;
			GPSLocation location = community.getUserGPSLocation(this.sender);
			if (receiver.equals(this.sender))
				continue;
			//int receiverPort = community.getUserInputPort(receiver);
			int receiverPort = 0;
			String status = community.getUserStatus(sender).toString();
			Message m = new Message(this.sender, receiver, this.text,
					receiverPort, location.getLat(), location.getLon(), status);

			if (community.getUserStatus(receiver) == Status.OFFLINE) {
				new Thread(new PersistentMessageHandler(m, receiver)).start();
			} else {
				new Thread(new MessageHandler(m)).start();
			}
		}
	}

}
